//
//  UIKImageView.swift
//  UIKImageView
//
//  Created by Fineland on 2021/3/8.
//

import UIKit

class UIKImageView: UIImageView {

    //下载操作的队列
    private var imgQueue: OperationQueue!
    //文件名称
    private(set) var fileName: String!
    //本地文件路径
    private(set) var filePath: URL!
    
    func imageUrl(_ url: String) -> Void {
        
        //是否为空？
        if "" != url {
            return updateImage(url)
        }
        fileName = ""
        filePath = nil
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */
    
    private func updateImage(_ url: String) -> Void {
        
        //缓存路径
        let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).last!
        //文件名称、路径
        fileName = url.components(separatedBy: "/").last!
        filePath = URL(fileURLWithPath: cachePath.appending("/\(fileName!)"))
        //本地图片
        if let imgData = try? Data(contentsOf: filePath) {
            let img = UIImage(data: imgData)
            self.image = img
            return
        }
        //是否合法？
        guard let tempURL = URL(string: url) else {
            return
        }
        //下载
        imgURL(tempURL)
    }
    
    private func imgURL(_ url: URL) -> Void {
        
        //下载队列
        if nil == imgQueue {
            imgQueue = OperationQueue()
        }
        //创建下载图片
        let operation = BlockOperation {
            if let imgData = try? Data(contentsOf: url) {
                //保存到doc目录下面
                try? imgData.write(to: self.filePath)
                //主线程刷新
                OperationQueue.main.addOperation({
                    self.image = UIImage(data: imgData)
                })
            }
        }
        //添加操作到队列中
        imgQueue.addOperation(operation)
    }
}
